import 'package:flutter/material.dart';

/// create at 2021/7/15
/// by yjl
/// describe：

class CustomMultiChildPage extends StatefulWidget {
  CustomMultiChildPage({Key? key}) : super(key: key);

  @override
  _CustomMultiChildPageState createState() => _CustomMultiChildPageState();
}

class _CustomMultiChildPageState extends State<CustomMultiChildPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("CustomMultiChildPage"),
      ),
      body: Container(
        color: Colors.blue,
        child: CustomMultiChildLayout(
          delegate: MyMultiChildLayoutDelegate(),
          children: [
            LayoutId(id: 1, child: FlutterLogo()),
            LayoutId(id: 2, child: FlutterLogo()),
            LayoutId(id: 3, child: FlutterLogo(size: 100,)),
            LayoutId(id: 4, child: Text("hello")),
            LayoutId(id: 5, child: Container(color: Colors.red)),
          ],
        ),
      ),
    );
  }
}


///向下传递约束，向上传递尺寸
class MyMultiChildLayoutDelegate extends MultiChildLayoutDelegate {
  late Size size1,size2,size3,size4,size5;
  double top = 100;

  @override
  Size getSize(BoxConstraints constraints) {
    // TODO: implement getSize
    return Size(400,400);
  }

  @override
  void performLayout(Size size) {
    if (hasChild(1)) {
       size1 = layoutChild(
          1,
          BoxConstraints(
              minHeight: 50, maxHeight: 50, minWidth: 50, maxWidth: 50));
      positionChild(1, Offset(0, top));
    }

    if (hasChild(2)) {
       size2 = layoutChild(
          2,
          BoxConstraints.tight(Size(80,80)));
      positionChild(2, Offset(size1.width, top+size1.height));
    }
    if (hasChild(3)) {
      size3 = layoutChild(
          3,
          BoxConstraints.loose(size));
      positionChild(3, Offset(size1.width+size2.width, top+size1.height+size2.height));
    }
    if (hasChild(4)) {
      size4 = layoutChild(
          4,
          BoxConstraints.loose(size));
      positionChild(4, Offset(0,0));
    }

    if (hasChild(5)) {
      size5 = layoutChild(
          5,
          BoxConstraints.tight(
            Size(
              size4.width, 5)
          ));
      positionChild(5, Offset(0,size4.height));
    }
  }

  @override
  bool shouldRelayout(covariant MultiChildLayoutDelegate oldDelegate) {
    return true;
  }
}
